#!/usr/bin/env node

var cp = require('child_process');
var exec = require('child_process').exec;
var program = require('commander');
var fs = require('fs-extra');
var AdmZip = require('adm-zip');


program
  .version('0.0.1')
  .option('-s, --sandbox', 'sandbox mode')
  .option('-b, --bundled', 'bundled mode')
  .option('-c, --cordova [command]', 'run a cordova command: [run, build]')
  .option('-p, --profile [profile]', 'using a profile: [development, production, mock, ...]')
  .parse(process.argv);

//模式，默认是bundled
var bundledMode = !program.sandbox;

//profile，默认为production
var profile = program.profile || 'production';

//android存到assets/下，ios存到当前目录下
var basePath = fs.existsSync('AndroidManifest.xml') ? 'assets/' : '';

// profile文件
var profileBasePath = basePath + 'app/changan/profile/';

var wwwPath = basePath + 'www';
var appPath = basePath + 'app';

/**
 * run
 */
removeApp();

clone(function(){

	if (bundledMode) {
		console.log('copy cordova stuff: %s to %s', wwwPath, appPath);
		fs.copySync(wwwPath, appPath);
	};

	//选中的profile文件
	var profileFile = profileBasePath + 'profile-' + profile + '.json';
	if (fs.existsSync(profileFile)){
		console.log('switch to profile: %s', profile);
		fs.copySync(profileFile, profileBasePath + 'profile.json');
	} else {
		console.error('profile [%s] not exists!', profile);
	}
});

function removeApp(){
	console.log('Clean app folder...');
	fs.removeSync(appPath);
}

function clone(next){

	console.log('Cloning Web Project into app folder...');

  var commands = [
  'git clone https://git.oschina.net/chameleon/exhibition-web.git ' + appPath,
  'cd ' + appPath,
  'git submodule init',
  'git submodule update'
  ];

	cp_clone = exec(commands.join(';'), function (error, stdout, stderr) {

			if (error !== null) {
	      console.log('clone error: ' + error);
	      return;
	    }

      //remove files
      var files = [
      'Gruntfile.js',
      'package.json',
      'server.js',
      'bower.json',
      '.git/'
      ];

      files.forEach(function(file){
        file = appPath + file;
        if (fs.existsSync(file))
          console.log('remove: %s', file);
          fs.removeSync(file);
      });

      next();
	});
	cp_clone.stdout.pipe(process.stdout);
	cp_clone.stderr.pipe(process.stderr);
}

// function zipupWWW(next){

// 	if (!fs.existsSync('www')) {
// 		console.error('www folder not exists, can not zip.');
// 		return;
// 	}

// 	console.log('Zip up www folder.');
// 	cp_zip = exec('zip -r Install/www.zip www/*', function(error, stdout, stderr){

// 		if (error !== null) {
//       console.log('zip error: ' + error);
//       return;
//     }

//     next();

// 	});
// }
